package com.Cfeng.XiaohuanChat.service.impl;

import com.Cfeng.XiaohuanChat.entity.ChatMessage;
import com.Cfeng.XiaohuanChat.repository.ChatMessageRepository;
import com.Cfeng.XiaohuanChat.service.ChatMessageService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;

/**
 * @author Cfeng
 * @date 2022/8/6
 */

@Service
@RequiredArgsConstructor
public class ChatMessageServiceImpl implements ChatMessageService {

    private final ChatMessageRepository chatMessageRepository;

    private final MongoTemplate mongoTemplate;

    //消息处理业务逻辑,只是加载世界频道的,userName唯一
    @Override
    public List<ChatMessage> findWorldLastTenMessage(String userName) {
        //只有世界频道,查找receiver为null的 即可
        Query query = new Query();
        //空字符串和null不同，所以寻常使用StringUtil的isEmptyOrNull
        Criteria criteria = new Criteria().orOperator(Criteria.where("receiver").is(null),Criteria.where("receiver").is(""));
        query.addCriteria(criteria).with(Sort.by(Sort.Direction.DESC,"createTime")).limit(10);
        List<ChatMessage> result = mongoTemplate.find(query,ChatMessage.class);
        //使用sort，选择Comparator排序器的comparing方法选择参数进行比较
        result.sort(Comparator.comparing(ChatMessage::getCreateTime));
        return result;
    }

    @Override
    public List<ChatMessage> findPrivateLastTenMessage(String senderName, String receiverName) {
        //在MongoDB数据库中diy查询
        Query query = new Query();
        Criteria criteria = new Criteria().andOperator(Criteria.where("receiver").is(senderName),Criteria.where("sender").is(receiverName)).andOperator(Criteria.where("receiver").is(receiverName),Criteria.where("sender").is(senderName));
        query.addCriteria(criteria).with(Sort.by(Sort.Direction.DESC,"createTime")).limit(10);
        List<ChatMessage> result = mongoTemplate.find(query,ChatMessage.class);
        //使用sort，选择Comparator排序器的comparing方法选择参数进行比较
        result.sort(Comparator.comparing(ChatMessage::getCreateTime));
        return result;
    }

    @Override
    public ChatMessage saveChatMessage(ChatMessage chatMessage) {
        return chatMessageRepository.save(chatMessage);
    }

    //模糊查询
    @Override
    public ChatMessage getChatMessage(String content) {
        return chatMessageRepository.findByContentContaining(content);
    }
}
